package com.csx.framework.springboot.sample.aop.controller;

import com.csx.framework.springboot.sample.aop.annotation.RepeatSubmit;
import com.csx.framework.springboot.sample.util.CommonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * <p> what does this class do ? </p>
 * <p> How does it work ?</p>
 * <p> Why does it do this ?</p>
 *
 * @author cuisongxu
 * @date 2024/12/19 周四 17:53
 */
@RestController
@RequestMapping("/aop")
public class RepeatSubmitController {

    private final Logger logger = LoggerFactory.getLogger(RepeatSubmitController.class);

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;


    /**
     * 提交订单令牌的缓存key
     */
    public static final String SUBMIT_ORDER_TOKEN_KEY = "order:submit:%s:%s";

    /**
     * 下单前获取令牌用于防重提交
     * @return
     */
    @GetMapping("/token")
    public String getOrderToken(){
        //获取登录账户. 实际场景从session中获取
        long accountNo = 123456;
        //随机获取32位的数字+字母作为token
        String token = CommonUtil.getStringNumRandom(32);
        //key的组成
        String key = String.format("submit",accountNo,token);
        //令牌有效时间是30分钟
        redisTemplate.opsForValue().set(key, String.valueOf(Thread.currentThread().getId()),30, TimeUnit.MINUTES);
        return token;
    }
    @RepeatSubmit(limitType = RepeatSubmit.Type.TOKEN)
    @GetMapping("/order")
    public String order(@RequestParam("products") String products) {
        logger.info("用户 {} 购买了商品: {}", "123456", products);
        return "购买成功";
    }
}
